//
//  YCCommonTool.m
//  YCVillageDoctor
//
//  Created by Mac on 2017/6/7.
//  Copyright © 2017年 zhangxiaoliang. All rights reserved.
//

#import "YCCommonTool.h"
#import "NSDate+YCExtension.h"

//获取手机IP

#import <ifaddrs.h>
#import <arpa/inet.h>
#import <sys/utsname.h>
#import <net/if.h>

@implementation YCCommonTool

static FMDatabase *_db;


+ (void)initialize
{
    
    // 1.打开数据库
    NSString *path = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"yuancheng.sqlite"];
    _db = [FMDatabase databaseWithPath:path];
    [_db open];
    
    
    [_db executeUpdate:@"CREATE TABLE IF NOT EXISTS yc_hospital_list (id integer PRIMARY KEY, ychospital blob NOT NULL, hospitalID text NOT NULL);"];
    
    [_db executeUpdate:@"CREATE TABLE IF NOT EXISTS yc_expert_list (id integer PRIMARY KEY, ycexpert blob NOT NULL, expertID text NOT NULL);"];
    
    [_db executeUpdate:@"CREATE TABLE IF NOT EXISTS yc_hosname_list (id integer PRIMARY KEY, ychosname blob NOT NULL, hosID text NOT NULL);"];
    
    [_db executeUpdateWithFormat:@"create table if not exists yc_myaddpatient_list(id integer primary key, ycmyadd blob not null, myaddID text not null);"];
    
    [_db executeUpdateWithFormat:@"create table if not exists yc_leavehospatient_list(id integer primary key, ycleavehos blob not null, leavehosID text not null);"];
    
    [_db executeUpdateWithFormat:@"create table if not exists yc_consultmepatient_list(id integer primary key, ycconsultme blob not null, consultmeID text not null);"];
    
    [_db executeUpdateWithFormat:@"create table if not exists yc_vippatient_list(id integer primary key, ycvip blob not null, vipID text not null);"];
    
    [_db executeUpdateWithFormat:@"create table if not exists yc_expert(id integer primary key, ycexpert blob not null, expertID text not null);"];
    
    // [_db close];
    
}

/**
 * 判断手机号
 *
 *  @param string 手机号
 *
 *  @return bool
 */
+ (BOOL)validatePhoneNumber:(NSString *)string
{
    //    NSString * MOBILE = @"^1[34578]\\d{9}$";
    //    NSPredicate *regextestMobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", MOBILE];
    //    return  [regextestMobile evaluateWithObject:string];
    
    //手机号以13， 15，18开头，八个 \d 数字字符
    //    NSString *phoneRegex = @"^((13[0-9])|(15[^4,\\D])|(18[0,0-9]))\\d{8}$";
    //    NSPredicate *phoneTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",phoneRegex];
    //    return [phoneTest evaluateWithObject:string];
    
    //    电信号段:133/153/180/181/189/177
    //    联通号段:130/131/132/155/156/185/186/145/176
    //    移动号段:134/135/136/137/138/139/150/151/152/157/158/159/182/183/184/187/188/147/178
    //    虚拟运营商:170
    
    NSString *MOBILE = @"^1(3[0-9]|4[57]|5[0-35-9]|8[0-9]|7[036-8])\\d{8}$";
    
    NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", MOBILE];
    
    return [regextestmobile evaluateWithObject:string];
    
}
/**
 *  判断密码
 *
 *  @param passWord 密码
 *
 *  @return bool
 */
+ (BOOL) validatePassword:(NSString *)passWord

{
    
    
    NSString *passWordRegex = @"^[a-zA-Z0-9]{6,20}+$";
    NSPredicate *passWordPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",passWordRegex];
    
    
    return [passWordPredicate evaluateWithObject:passWord];
    
    
}

/**
 *  判断 token是否存在 和token_token是否过期
 *
 *  @return BOOL
 */
+(BOOL)tokenExistAndAccess_tokenExpire
{
    
    NSUserDefaults *def = [NSUserDefaults standardUserDefaults];
    
    NSString *token = [def objectForKey:access_token];
    
    if (token && [NSDate secondsToNowDateFromPastDate]) {
        
        return YES;
    }else{
        
        return NO;
    }
    
    
}

//判断是什么格式
+ (BOOL) imageHasAlpha: (UIImage *) image
{
    CGImageAlphaInfo alpha = CGImageGetAlphaInfo(image.CGImage);
    return (alpha == kCGImageAlphaFirst ||
            alpha == kCGImageAlphaLast ||
            alpha == kCGImageAlphaPremultipliedFirst ||
            alpha == kCGImageAlphaPremultipliedLast);
}

//图片转换base64
+ (NSString *) base64ImageData: (UIImage *) image
{
    NSData *imageData = nil;
    NSString *mimeType = nil;
    
    if ([self imageHasAlpha: image]) {
        imageData = UIImagePNGRepresentation(image);
        mimeType = @"image/png";
    } else {
        imageData = UIImageJPEGRepresentation(image, 0.09f);
        mimeType = @"image/jpg";
    }
    
    return [NSString stringWithFormat:@"data:%@;base64,%@", mimeType,
            [imageData base64EncodedStringWithOptions: NSDataBase64Encoding64CharacterLineLength]];
    
}


+ (NSString *)getErrorStr:(NSString *)errorCode {
    
    NSString *str = @"";
    errorCode = [errorCode substringToIndex:5];
    if ([errorCode isEqualToString:@"00001"]) {
        str = @"系统错误";
    }else if ([errorCode isEqualToString:@"00002"]) {
        str = @"appid 或 appsecret 不存在";
    }else if ([errorCode isEqualToString:@"00003"]) {
        str = @"验签未通过";
    }else if ([errorCode isEqualToString:@"00004"]) {
        str = @"Access_token 已过期";
    }else if ([errorCode isEqualToString:@"00005"]) {
        str = @"Access_token 不存在";
    }else if ([errorCode isEqualToString:@"00006"]) {
        str = @"不合法的凭证类型";
    }else if ([errorCode isEqualToString:@"00007"]) {
        str = @"传递的参数值不能正确";
    }else if ([errorCode isEqualToString:@"00008"]) {
        str = @"Access_token 不能为空";
    }else if ([errorCode isEqualToString:@"00009"]) {
        str = @"未绑定手机号";
    }else if ([errorCode isEqualToString:@"00010"]) {
        str = @"member_id 空或者不正确";
    }else if ([errorCode isEqualToString:@"00011"]) {
        str = @"只能以 post 方式提交数据";
    }else if ([errorCode isEqualToString:@"00012"]) {
        str = @"用户名或者密码错误";
    }else if ([errorCode isEqualToString:@"00013"]) {
        str = @"验证码错误";
    }else if ([errorCode isEqualToString:@"00014"]) {
        str = @"已经签过到";
    }else if ([errorCode isEqualToString:@"00015"]) {
        str = @"解析 post 的 json 出现异常";
    }
    return str;
}


+(NSArray *)queryHosnames
{
    // 根据请求参数生成对应的查询SQL语句
    NSString *sql =@"SELECT * FROM yc_hosname_list ORDER BY hosID DESC LIMIT 400;";
    // 执行SQL
    FMResultSet *set = [_db executeQuery:sql];
    NSMutableArray *hosNames = [NSMutableArray array];
    while (set.next) {
        NSData *hosNameData = [set objectForColumnName:@"ychosname"];
        NSDictionary *hospital = [NSKeyedUnarchiver unarchiveObjectWithData:hosNameData];
        [hosNames addObject:hospital];
    }
    return hosNames;
}

+(void)saveHosname:(NSArray *)hosnames
{
    // 要将一个对象存进数据库的blob字段,最好先转为NSData
    // 一个对象要遵守NSCoding协议,实现协议中相应的方法,才能转成NSData
    for (NSDictionary *hosname in hosnames) {
        // NSDictionary --> NSData
        
        NSData *ychosnamelData = [NSKeyedArchiver archivedDataWithRootObject:hosname];
        [_db executeUpdateWithFormat:@"INSERT INTO yc_hosname_list(ychosname, hosID) VALUES (%@, %@);", ychosnamelData, hosname[@"HOS_ID"]];
    }
}


// 根据字符串，行间距，字体大小，最大宽度 获取label的高度
+ (CGFloat) heightWithStr:(NSString *)str lineSpacing:(CGFloat)lineSpacing fontSize:(CGFloat)size maxLabelWidth:(CGFloat)MaxLabelWidth{
    
    if (str==nil) return 25;
    
    NSMutableAttributedString *attrStr = [[NSMutableAttributedString alloc] initWithString:str];
    
    NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];
    
    if (lineSpacing != 0) {
        
        style.lineSpacing = lineSpacing;
        [attrStr addAttribute:NSParagraphStyleAttributeName value:style range:NSMakeRange(0, attrStr.length)];
    }
    
    //    3.2. 计算文字的高度，根据 label 的宽最大度和行间距
    NSDictionary *dictonary = @{
                                NSFontAttributeName : [UIFont systemFontOfSize:size],
                                NSParagraphStyleAttributeName : style
                                };
    
    CGFloat height = [str boundingRectWithSize:CGSizeMake(MaxLabelWidth, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:dictonary context:nil].size.height;
    return height;
}

// Get IP Address
+(NSString *)getIPAddress
{
    NSString *address = @"error";
    struct ifaddrs *interfaces = NULL;
    struct ifaddrs *temp_addr = NULL;
    int success = 0;
    // retrieve the current interfaces - returns 0 on success
    success = getifaddrs(&interfaces);
    if (success == 0) {
        // Loop through linked list of interfaces
        temp_addr = interfaces;
        while(temp_addr != NULL) {
            if(temp_addr->ifa_addr->sa_family == AF_INET) {
                // Check if interface is en0 which is the wifi connection on the iPhone
                if([[NSString stringWithUTF8String:temp_addr->ifa_name] isEqualToString:@"en0"]) {
                    // Get NSString from C String
                    address = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_addr)->sin_addr)];
                }
            }
            temp_addr = temp_addr->ifa_next;
        }
    }
    // Free memory
    freeifaddrs(interfaces);
    return address;
}



@end
